<!--
 * @Description: 产品栏目管理
 * @Author: money
 * @Date: 2021-06-24 17:03:34
 * @LastEditors: Zlou
 * @LastEditTime: 2021-07-02 15:56:24
-->
<template>
  <div>
    <!-- 添加按钮 -->
    <div>
      <el-button @click="toAdd" type="primary" class="btn" size="small"
        >添加</el-button
      >
    </div>
    <!-- 表格 -->
    <div>
      <el-table
        size="mini"
        :data="tableData"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" align="center" width="100">
        </el-table-column>
        <el-table-column prop="id" label="栏目编号" align="center">
        </el-table-column>
        <el-table-column prop="name" label="名称" align="center">
        </el-table-column>
        <el-table-column label="图标" align="center">
          <template slot-scope="scope">
            <el-image
              style="width: 30px; height: 30px"
              :src="scope.row.icon"
              :preview-src-list="[scope.row.icon]"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="排序号" align="center">
        </el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template slot-scope="scope">
            <el-button
              type="text"
              class="warning_info"
              size="small"
              icon="el-icon-edit-outline"
              @click="toEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              class="red_info"
              type="text"
              size="small"
              icon="el-icon-delete"
              @click="toDelete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="pagination-div">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.page"
        :page-sizes="[2, 5, 10, 15, 20, 30]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 模态框 对话框-->
    <el-dialog
      title="添加栏目信息"
      :visible.sync="visible"
      :before-close="toClose"
    >
      <el-form :model="form" :rules="rules" ref="ruleForm" size="small">
        <el-form-item
          prop="name"
          label="栏目名称"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="num" label="序号" :label-width="formLabelWidth">
          <el-input v-model.number="form.num" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="icon" label="图标" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="toClose">取 消</el-button>
        <el-button type="primary" @click="toSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageQuery, saveOrUpdate, deleteById } from "@/api/proCategory";
import { showFileURL, uploadFileURL } from "@/utils/config";
export default {
  data() {
    return {
      showFileURL,
      uploadFileURL,
      // 表格展示的数据
      tableData: [],
      // 分页参数
      params: {
        page: 1,
        pageSize: 10,
      },
      // 总条数
      total: 0,
      // 加载
      loading: false,
      // 表单数据
      form: {},
      // 表单控件标题的宽度
      formLabelWidth: "80px",
      // 模态框的标题
      title: "",
      // 图片url
      imageUrl: "",
      // 模态框的显示与隐藏
      visible: false,
      // 校验规则
      rules: {
        name: [{ required: true, message: "请输入栏目名称", trigger: "blur" }],
        icon: [
          { required: true, message: "请上传栏目图标", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    // loading
    params: {
      handler() {
        this.queryData();
      },
      deep: true,
    },
  },
  computed: {},
  methods: {
    // 获取产品分类数据
    async queryData() {
      this.loading = true;
      // 处理数据
      let temp = {
        ...this.params,
      };
      // 遍历对象
      for (let key in temp) {
        if (!temp[key]) {
          delete temp[key];
        }
      }
      let res = await pageQuery(temp);
      this.tableData = res.data.list;
      this.total = res.data.total;
      // 加载完毕
      this.loading = false;
    },
    // 新增栏目信息
    toAdd() {
      // 清空表单数据
      (this.form = {}), (this.imageUrl = ""), (this.title = "添加产品信息");
      this.visible = true;
    },
    // 关闭模态框
    toClose() {
      // 重置表单验证
      this.$refs.ruleForm.resetFields();
      //  超时调用
      setTimeout(() => {
        this.visible = false;
      }, 200);
    },
    // 模态框确认按钮事件处理程序
    toSave() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          console.log("校验通过");
          let res = await saveOrUpdate(this.form);
          // 提示用户保存成功，刷新表格数据，关闭模态框
          this.$notify.success({
            title: "",
            message: res.message,
          });
          this.queryData();
          this.toClose();
        } else {
          return false;
        }
      });
    },
    // 编辑
    toEdit(row) {
      // 设置表单数据
      (this.form = { ...row }),
        (this.imageUrl = this.form.icon),
        (this.title = "编辑产品信息");
      this.visible = true;
    },
    // 删除
    toDelete(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteById({ id })
            .then((res) => {
              this.$message({
                message: "删除栏目信息成功",
                type: "success",
              });
            })
            .catch((e) => {
              this.$message.error("删除栏目信息失败");
            });
          this.queryData();
        })
        .catch(() => {
          this.$notify.info({
            title: "取消",
            message: "已取消删除",
          });
        });
    },
    // 图片上传成功的回调函数
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.icon = showFileURL + res.data.id;
    },
    // 图片上传之前的回调函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 每页显示的条数发生变化时的事件处理程序
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.params = {
        page: 1,
        pageSize: val,
      };
    },
    // 当前页码发生变化时的时的事件处理程序
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.params.page = val;
    },
  },
  created() {
    this.queryData();
  },
  mounted() {},
};
</script>
<style scoped>
.btn {
  margin: 10px;
  padding: 7px, 15px;
  /* background-color: rgb(44, 181, 172); */
}
</style>